<template>
  <div>
    <!-- 添加书籍对话框 -->
    <el-dialog title="添加图书" :visible.sync='visible' width="600px" @closed="cancel" append-to-body>
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
        <el-form-item label="图书名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入书籍名称" />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-select
            v-model="AuthorValue"
            filterable
            allow-create
            default-first-option
            placeholder="请选择作者"
            @change="isAddAuthor"
            :filter-method="AuthorKeyChange"

            >
            <el-option
              v-for="item in AuthorOptions"
              :key="item.author"
              :label="item.author"
              :value="item.authorValue"
              >
              <span style="float: left">{{ item.author }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">编号:{{ item.authorValue }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出版社" prop="publish">
          <el-select
            v-model="PublishValue"
            filterable
            allow-create
            default-first-option
            placeholder="请选择出版社"
            @change="isAddPublish"
            :filter-method="PublishKeyChange"
            >
            <el-option v-for="item in PublishOptions" :key="item.publish" :label="item.publish"
              :value="item.publishValue">
              <span style="float: left">{{ item.publish }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">编号:{{ item.publishValue }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="addForm.isbn" placeholder="请输入ISBN" />
        </el-form-item>

        <el-form-item label="介绍" prop="introduction">
          <el-input v-model="addForm.introduction" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="语言" prop="language">
          <el-select v-model="LanguageValue" filterable allow-create default-first-option placeholder="请选择语言"
            @change="isAddLanguage">
            <el-option v-for="item in LanguageOptions" :key="item.language" :label="item.language"
              :value="item.languageValue">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 分类多选框 -->
<!--        <el-form-item label="图书分类" prop="categoryId">-->
<!--          <el-select v-model="CategoryValue" multiple filterable allow-create placeholder="请选择" @change="isAddCategory">-->
<!--            <el-option v-for="item in CategoryOptions" :key="item.value" :label="item.name" :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="价格" prop="price">
          <el-input v-model="addForm.price" placeholder="请输入价格" />
        </el-form-item>

        <el-form-item label="数量" prop="number">
          <el-input v-model="addForm.number" placeholder="请输入数量" />
        </el-form-item>





        <el-form-item label="位置" prop="location">
          <el-input v-model="addForm.location" placeholder="请输入位置" />
        </el-form-item>


        <!-- 上传图书封面 -->
<!--        <el-form-item label="图书封面">-->

<!--          <imageUpload @getPicUrl="handlePicUrl">-->

<!--          </imageUpload>-->


<!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(addForm)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!-- <button @click="test">点击</button> -->
    </el-dialog>

  </div>
</template>

<script>
import { getAllBook, addBook,searchDict, getDict, addDict } from '@/api/request.js'
import imageUpload from '@/components/ManagementTable/ImageUpload.vue'
export default {
  name: "addBookTable",
  props: [""],
  components: {
    imageUpload
  },
  data() {
    return {
      visible: true,
      //表单验证
      rules: {
        name: [{ required: true, message: '图书名不能为空', trigger: 'blur' }],
        author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
        publish: [{ required: true, message: '出版社不能为空', trigger: 'blur' }],
        isbn: [{ required: true, message: 'ISBN不能为空', trigger: 'blur' }],
        // introduction:[{required: true, message: '介绍不能为空', trigger: 'blur'}],
        language: [{ required: true, message: '语言不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        number: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        // categoryId: [{ required: true, message: '图书分类不能为空', trigger: 'blur' }],
        location:[{required: true, message: '请输入位置', trigger: 'blur'}],
        // createBy: [{ required: true, message: '创建者不能为空', trigger: 'blur' }],

      },

      //添加图书表单
      addForm: {
        url: "",
        createTime: '',
        publish: '',
        language: '',
        author: '',
        categoryId:"1",
        isDelete:'0',
        createBy:this.$store.state.user.userId
      },
      // 添加出版社选择框
      PublishOptions: [],
      //出版社编号
      PublishValue: "",

      //添加字典参数
      queryAddDict: {
        type: "",
        value: [],
      },
      //添加语言选择框
      LanguageOptions: [],
      //回传的语言编号
      LanguageValue: "",
      //作者选择框
      AuthorOptions: [],
      //作者编号
      AuthorValue: '',
      //分类选项
      CategoryOptions: [],
      //分类编号
      CategoryValue: [],
      UserValue:'',
      // 用户选择框
      UserOptions:[],
      //用户字典参数
      queryUserDict: {
        type: "username"
      },
      //出版社字典参数
      queryPublishDict: {
        type: "publish"
      },
      //作者字典参数
      queryAuthorDict: {
        type: "author"
      },
      //语言字典参数
      queryLanguageDict: {
        type: "language"
      },
      //分类字典参数
      queryCategoryIdDict: {
        type: "category"
      },
      //上传文件
      fileList: [],
      formData: "", // 初始化的上传
    }
  },
  created() {
    // this.getAllPublish()
    this.getAllLanguage()
    // this.getAllAuthor()
    this.getAllCategory()
    this.getAllUser()
    // console.log('当前id',this.$store.state.user.userId)
  },

  methods: {
    //模糊查询作者
    AuthorKeyChange:function(inputKey){
      if(inputKey != ""){
        searchDict({ type: "author",keyWord:inputKey}).then(res=>{
        // console.log('获取到的模糊查询',res)
        this.AuthorOptions = res.data
      }).catch(err=>{
        console.log('作者模糊查询失败')
      })
      }else{
        this.AuthorOptions = []
      }
  },





  //出版社模糊查询
  PublishKeyChange:function(inputKey){
    if(inputKey != ""){
       searchDict({ type: "publish",keyWord:inputKey}).then(res=>{
        // console.log('获取到的模糊查询',res)
        this.PublishOptions = res.data
      }).catch(err=>{
        console.log('出版社模糊查询失败')
      })
    }else{
      this.PublishOptions =[]
    }

  },


    handleCreate(){
      this.addForm.createBy =  this.UserValue
      console.log('处理创建人',this.addForm.createBy)
    },
    /**
     * 查询所有用户
     */
     getAllUser(){
      getDict(this.queryUserDict).then(res => {
        // console.log('查询用户接口', res)
        this.UserOptions = res.data
      }).catch(err => {
        console.log('查询用户接口失败', err)
      })
    },

    StrCategoryId(){
      var tempCategory = ''
      for(var i=0;i<this.CategoryValue.length;i++){
        if(i==0){
          tempCategory+=this.CategoryValue[i]
        }else{
          tempCategory =tempCategory+ ','+this.CategoryValue[i]
        }
      }
      this.addForm.categoryId = tempCategory;

    },
    /**
     * 查询所有出版社
     */
    getAllPublish() {
      getDict(this.queryPublishDict).then(res => {
        // console.log('查询出版社接口', res)
        // this.PublishOptions = res.data
      }).catch(err => {
        console.log('查询出版社接口失败', err)
      })
    },
    /**
     * 查询所有语言
     */
    getAllLanguage() {
      getDict(this.queryLanguageDict).then(res => {
        // console.log('查询语言接口', res)
        this.LanguageOptions = res.data
      }).catch(err => {
        console.log('查询语言接口失败', err)
      })
    },

    /**
     * 查询所有作者
     */
    getAllAuthor() {
      getDict(this.queryAuthorDict).then(res => {
        // console.log('查询作者接口', res)
        this.AuthorOptions = res.data
      }).catch(err => {
        console.log('查询语言接口失败', err)
      })
    },
    /**
   * 查询所有分类
   */
    getAllCategory() {
      getDict(this.queryCategoryIdDict).then(res => {
        // console.log('查询分类接口', res)
        this.CategoryOptions = res.data
      }).catch(err => {
        console.log('查询分类接口失败', err)
      })
    },
    /**
     *@functionName:     zxh
     *@description:判断是否要新增作者,如果需要则添加
     *@author: zxh
     *@date: 2024-01-09 11:24:10
    */
    isAddAuthor() {
      // console.log('作者变了')
      var add = true
      for (var i = 0; i < this.AuthorOptions.length; i++) {
        if (this.AuthorValue == this.AuthorOptions[i].authorValue) {
          add = false
        }
      }
      this.addForm.author = this.AuthorValue
      if (add) {
        this.$confirm('是否添加'+this.addForm.author,'未查询到该作者', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addDict({
          "type": "author",
          "value": [
            this.AuthorValue
          ]
        }).then(res => {
          console.log('添加作者成功', res)
          this.addForm.author = res.data
        }).catch(err => {
          console.log('添加作者失败')
        })
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        }).catch(() => {
          // test
          this.AuthorValue = ""
          this.AuthorOptions = []

        });


      }

    },



    isAddPublish() {
      var add = true
      for (var i = 0; i < this.PublishOptions.length; i++) {
        if (this.PublishValue == this.PublishOptions[i].publishValue) {
          add = false
        }
      }
      this.addForm.publish = this.PublishValue
      if (add) {

        this.$confirm('是否添加'+this.addForm.publish, '未查询到出版社', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addDict({
          "type": "publish",
          "value": [
            this.PublishValue
          ]
        }).then(res => {
          console.log('添加出版社成功', res)
          this.addForm.publish = res.data
        }).catch(err => {
          console.log('添加出版社失败')
        })

          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        }).catch(() => {
          this.PublishValue = ''
          this.PublishOptions = []
        });
      }

    },



    isAddLanguage() {
      var add = true
      for (var i = 0; i < this.LanguageOptions.length; i++) {
        if (this.LanguageValue == this.LanguageOptions[i].languageValue) {
          add = false
        }
      }
      this.addForm.language = this.LanguageValue
      if (add) {
        this.$confirm('此操作将添加语言, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addDict({
          "type": "language",
          "value": [
            this.LanguageValue
          ]
        }).then(res => {
          console.log('添加语言成功', res)
          this.addForm.language = res.data
        }).catch(err => {
          console.log('添加语言失败')
        })
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消添加'
          });
        });

      }

    },


    isAddCategory() {
      var delIndex
      for (var i = 0; i < this.CategoryValue.length; i++) {
        // 如果其中一项是字符串，则进行添加字符串
        if (typeof(this.CategoryValue[i])=="string") {
          // add = false
          delIndex = i;
          this.$confirm('此操作将添加分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addDict({
            "type": "category",
            "value":[
              this.CategoryValue[delIndex]
            ]
          }).then(res=>{
            // console.log('添加分类成功',res)
            console.log('id',this.CategoryValue[delIndex],"resdata",res.data[0])
            this.CategoryValue[delIndex] = res.data[0]
          }).catch(err=>{
            console.log('添加分类失败')
          })
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消添加'
          });
        });

        }
      }
    },

    /** 提交按钮 */
    submitForm: function (data) {
      //点击提交时将提交时间传给addForm
      this.handleTime()
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          // alert('确认新增书籍!');
          // this.StrCategoryId()
          addBook(data).then(res => {
            this.addForm = {}
            // 将弹窗关闭
            this.$emit("closeAddTable")
          }).catch(err => {
            console.log(err)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    /**
     * 点击取消按钮
     */
    cancel() {
      this.$emit("closeAddTable")
    },
    handleTime() {
      // 创建一个 Date 对象
      var today = new Date();

      // 获取年、月、日、时、分、秒
      var year = today.getFullYear();
      var month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
      var day = today.getDate();
      var hours = today.getHours();
      var minutes = today.getMinutes();
      var seconds = today.getSeconds();

      // 格式化输出
      var formattedTime = year + "-" +
        (month < 10 ? "0" : "") + month + "-" +
        (day < 10 ? "0" : "") + day + " " +
        (hours < 10 ? "0" : "") + hours + ":" +
        (minutes < 10 ? "0" : "") + minutes + ":" +
        (seconds < 10 ? "0" : "") + seconds;
      this.addForm.createTime = formattedTime

      // console.log(this.addForm.createTime);
      // "2023-11-08 19:05:05"
    },

    // 从图片上传组件返回图片的url
    handlePicUrl(data) {
      this.addForm.url = data;
    },

    // 重置infoData
    restInfoData() {
      this.infoData = {}
    },
  },
}

</script>

<style></style>
